<?php

namespace app\api\controller;

use app\model\MemberBuyer;
use app\model\Withdraw;
use app\model\Order;
use app\model\MemberBuyerPlatformInfo;
use app\model\MemberBuyerInfo;
use app\model\Appeal;
use think\facade\Request;
use think\DB;
use app\common\validate\Member as MemberValidate;
use think\Validate;
use think\route\Resource;

class Member
{

    public function message()
    {
        $data = DB::name('message')
            ->field('id,title,addtime,flag')
            ->where('userid', session('memberInfo.userid'))
            ->where('usertype', 1)
            ->order(['flag', 'addtime' => 'desc'])
            ->paginate(20);
        return json(['code' => 0, 'data' => $data]);
    }

    public function message_detail()
    {
        $data = DB::name('message')
            ->where('id', Request::get('id'))
            ->where('userid', session('memberInfo.userid'))
            ->where('usertype', 1)
            ->find();
        DB::name('message')->where('id', Request::get('id'))->update(['flag' => 1]);
        return json(['code' => 0, 'data' => $data]);
    }

    public function index()
    {
        $unread = DB::name('message')
            ->where('userid', session('memberInfo.userid'))
            ->where('usertype', 1)
            ->where('flag', 0)
            ->count();
        $memberInfo = MemberBuyer::field('amount,coin,userid,status')->where('userid', session('memberInfo.userid'))->find();
        $notice = DB::name('notice')
            ->field('topic')
            ->where('type', 2)
            ->where('starttime', '<', \tool\Date::date())
            ->where('endtime', '>', \tool\Date::date())
            ->where('status', 1)
            ->order(['addtime' => 'desc'])
            ->limit(3)
            ->column('topic');
        $app_setting = DB::name('app_setting')->column('value', 'name');
        $app_setting['bind_taobao_detail_hightquality_tkl'] = DB::name('tkl')->where('key', 'tkl')->value('value');

        $app_setting['binding_device'] = false;
        $system_type = Request::get('system_type');
        $device_id = Request::get('device_id');
        if ($system_type == 'ios' && !empty($device_id)) {
            $row = DB::name('member_buyer_binding_device')
                ->where('system_type', 'ios')
                ->where('device_id', $device_id)
                ->find();
            if ($row) {
                if ($row['userid'] != session('memberInfo.userid')) {
                    $cellphone = MemberBuyer::where('userid', $row['userid'])->value('cellphone');
                    $cellphone[3] = '*';
                    $cellphone[4] = '*';
                    $cellphone[5] = '*';
                    $cellphone[6] = '*';
                    $app_setting['binding_device'] = $cellphone;
                }
            } else {
                DB::name('member_buyer_binding_device')
                    ->insert([
                        'userid' => session('memberInfo.userid'),
                        'system_type' => 'ios',
                        'device_id' => $device_id,
                    ]);
            }
        }

        $ip_mac = Request::get('ip_mac');
        if ($system_type == 'android' && !empty($ip_mac)) {
            $row = DB::name('member_buyer_binding_device')
                ->where('system_type', 'android')
                ->where('ip_mac', $ip_mac)
                ->find();
            if ($row) {
                if ($row['userid'] != session('memberInfo.userid')) {
                    $cellphone = MemberBuyer::where('userid', $row['userid'])->value('cellphone');
                    $cellphone[3] = '*';
                    $cellphone[4] = '*';
                    $cellphone[5] = '*';
                    $cellphone[6] = '*';
                    $app_setting['binding_device'] = $cellphone;
                }
            } else {
                DB::name('member_buyer_binding_device')
                    ->insert([
                        'userid' => session('memberInfo.userid'),
                        'system_type' => 'android',
                        'ip_mac' => $ip_mac,
                    ]);
            }
        }

        return json(['code' => 0, 'data' => [
            'unread' => $unread,
            'amount' => $memberInfo['amount'],
            'coin' => $memberInfo['coin'],
            'member_status' => $memberInfo['status'],
            'userid' => session('memberInfo.userid'),
            'notice' => $notice,
            'app_setting' => $app_setting
        ]]);
    }

    public function my()
    {
        $reData = [];
        $memberInfo = MemberBuyer::where('userid', session('memberInfo.userid'))->find();
        $unread = DB::name('message')
            ->where('userid', session('memberInfo.userid'))
            ->where('usertype', 1)
            ->where('flag', 0)
            ->count();
        $reData['id'] = $memberInfo['userid'];
        $reData['unread'] = $unread;
        $reData['phone'] = $memberInfo['cellphone'];
        $reData['score'] = $memberInfo->info['score'];
        $reData['coin'] = $memberInfo['coin'];
        $reData['avatar'] = $memberInfo['avatar'];
        $reData['income'] = Order::where('receiverid', session('memberInfo.userid'))->where('status', 6)->sum('commission');
        $reData['withdrawing'] = Withdraw::where('userid', session('memberInfo.userid'))->where('status', 0)->count();
        $reData['order_count'] = 0;
        $reData['order_count2'] = 0;
        $reData['order_count3'] = 0;
        $reData['order_count4'] = 0;
        $reData['order_count5'] = 0;

        $orderDta = Order::field('count(status) c,status')->where('receiverid', session('memberInfo.userid'))->group('status')->select();
        foreach ($orderDta as $vo) {
            $reData['order_count' . $vo->getData('status')] = $vo['c'];
            $reData['order_count'] += $vo['c'];
        }

        return json(['code' => 0, 'data' => $reData]);
    }


    public function refresh()
    {
        $memberInfo = MemberBuyer::where('userid', session('memberInfo.userid'))->find();
        session('memberInfo', clone $memberInfo);
        unset($memberInfo['password']);
        unset($memberInfo['MemberBuyerInfo']);
        return json([
            'code' => 0,
            'data' => $memberInfo
        ]);
    }

    public function login_post()
    {
        $validate = new MemberValidate;
        if (!$validate->scene('login')->check(Request::post())) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        }
        $phone = Request::post('cellphone');
        $password = Request::post('password');
        $restul = MemberBuyer::login($phone, $password);
       // $restul['msg'] = lang($restul['code']);
        return json($restul);
    }

    public function logout()
    {
        session('memberInfo', null);
        return json([
            'code' => 0
        ]);
    }

    public function register_post()
    {
        $validate = new MemberValidate;
        if (!$validate->scene('register')->check(Request::post())) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        }
        return json(MemberBuyer::register(Request::post()));
    }

    public function password_find_post()
    {
        $validate = new MemberValidate;
        if (!$validate->scene('password_find')->check(Request::post())) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        }

        $memberBuyer = new MemberBuyer();
        $memberInfo = $memberBuyer->phoneGetUserInfo(Request::post('cellphone'));
        if (!$memberInfo) {
            return json([
                'code' => 4003,
                'msg' => lang(4003)
            ]);
        }

        if ($memberBuyer->edit_pwd($memberInfo['userid'], Request::post('password'))) {
            return json($memberBuyer->login(Request::post('cellphone'), Request::post('password')));
        } else {
            return json([
                'code' => 1
            ]);
        }

    }

    public function edit_pwd_post()
    {
        $validate = new MemberValidate;
        if (!$validate->scene('edit_pwd')->check(Request::post())) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        }
        $memberBuyer = new MemberBuyer();
        if (!$memberBuyer->verifyPssword(Request::post('oldpassword'), session('memberInfo.password'))) {
            return json([
                'code' => 1,
                'msg' => '旧密码不正确'
            ]);
        }
        session('memberInfo.password', $memberBuyer->convertedPssword(Request::post('password')));
        return json($memberBuyer->edit_pwd(session('memberInfo.userid'), Request::post('password')));
    }

    public function platform()
    {
        if (Request::get('type')) {
            $data = MemberBuyerPlatformInfo::field('*,status statusText')->where('userid', session('memberInfo.userid'))
                ->where('type', Request::get('type'))
                ->find();
        } else {
            $platform = MemberBuyerPlatformInfo::field('id,type,account,isaccept,status statusText,hq_account_status')->where('userid', session('memberInfo.userid'))
                ->select();
            $data = [];
            foreach ($platform as $vo) {
                $data[] = $vo;
            }
        }
        return json([
            'code' => 0,
            'data' => $data
        ]);
    }

    public function platform_isaccept()
    {
        $dataRow = MemberBuyerPlatformInfo::field('status')->where('id', Request::get('id'))
            ->where('userid', session('memberInfo.userid'))
            ->find();

        if (!$dataRow) {
            return json([
                'code' => 1,
                'msg' => '账号不存在'
            ]);
        }
        if ($dataRow['status'] != 1) {
            return json([
                'code' => 1,
                'msg' => $dataRow['StatusText']
            ]);
        }

        $affectedRows = MemberBuyerPlatformInfo::where('id', Request::get('id'))
            ->where('userid', session('memberInfo.userid'))->update([
                'isaccept' => Request::get('isaccept')
            ]);

        if ($affectedRows !== false) {
            return json([
                'code' => 0
            ]);
        } else {
            return json(['code' => 1, 'msg' => '操作失败']);
        }
    }

    public function platform_post()
    {
        // $memberBuyer = MemberBuyer::where('userid', session('memberInfo.userid'))->find();
        // if ($memberBuyer->getData('idverifystatus') != 2 || !$memberBuyer['qq'] || !$memberBuyer['bankname']) {
        //     return json([
        //         'code' => 1,
        //         'msg' => '请先完善身份信息,银行绑定信息,QQ信息'
        //     ]);
        // }
        if (Request::post('type') == 1) {
            $validate = Validate::make([
                'type' => 'require|integer',
                'account' => 'require',
                'receiver_name' => 'require',
                'receiver_phone' => ['require', 'regex' => '/^1[3|4|5|6|7|8|9][0-9]\d{8}$/'],
                'receiver_addr_province' => 'require|integer',
                'receiver_addr_city' => 'require|integer',
                'receiver_addr_county' => 'require|integer',
                'receiver_addr_content' => 'require',
                'sex' => 'require|integer',
                'age' => 'require|integer',
                'credit_rating' => 'require|integer',
                // 'ordernumber_any' => 'require',
                // 'fav_cat_1' => 'require|integer',
                // 'fav_cat_2' => 'require|integer',
                // 'fav_cat_3' => 'require|integer',
                'credit_rating_img_url' => 'require',
                'realname_verify_img_url' => 'require',
                // 'huabei_img_url' => 'require',
            ])->message([
                'account.require' => '请填写淘宝账号名',
                'receiver_name.require' => '请填写收货人姓名',
                'receiver_phone.require' => '请填写收货人手机',
                'receiver_phone.regex' => '收货人手机格式不正确',
                'receiver_addr_province.require' => '请选择收货人地址_省',
                'receiver_addr_city.require' => '请选择收货人地址_市',
                'receiver_addr_county.require' => '请选择收货人地址_县区',
                'receiver_addr_content.require' => '请填写收货人详细地址',
                'sex' => '请选择性别',
                'age.require' => '请填写年龄',
                'age.integer' => '填写的年龄应该为数字',
                'credit_rating' => '请选择信誉等级',
                // 'ordernumber_any.require' => '请填写任意一个订单号',
                // 'fav_cat_1' => '请选择购物类目1',
                // 'fav_cat_2' => '请选择购物类目2',
                // 'fav_cat_3' => '请选择购物类目3',
                'credit_rating_img_url.require' => '请上传信誉等级图片',
                'realname_verify_img_url.require' => '请上传实名认证图片',
                // 'huabei_img_url.require' => '请上传花呗图片',
            ]);
        } else if (Request::post('type') == 2) {
            $validate = Validate::make([
                'type' => 'require|integer',
                'account' => 'require',
                'receiver_name' => 'require',
                'receiver_phone' => ['require', 'regex' => '/^1[3|4|5|6|7|8|9][0-9]\d{8}$/'],
                'receiver_addr_province' => 'require|integer',
                'receiver_addr_city' => 'require|integer',
                'receiver_addr_county' => 'require|integer',
                'receiver_addr_content' => 'require',
                'credit_rating_img_url' => 'require',
                'realname_verify_img_url' => 'require',
                'huabei_img_url' => 'require',
            ])->message([
                'account.require' => '请输入账号(手机号)',
                'receiver_name.require' => '请填写收货人姓名',
                'receiver_phone.require' => '请填写收货人手机',
                'receiver_phone.regex' => '收货人手机格式不正确',
                'receiver_addr_province.require' => '请选择收货人地址_省',
                'receiver_addr_city.require' => '请选择收货人地址_市',
                'receiver_addr_county.require' => '请选择收货人地址_县区',
                'receiver_addr_content.require' => '请填写收货人详细地址',
                'credit_rating_img_url.require' => '请上传个人图片',
                'realname_verify_img_url.require' => '请上收货地址图片',
                'huabei_img_url.require' => '请上微信账号图片',
            ]);
        }


        if (!$validate->check(Request::post(''))) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        }

        $dataRow = MemberBuyerPlatformInfo::where('type', Request::post('type'))
            ->where('account', Request::post('account'))
            ->where('userid != ' . session('memberInfo.userid'))
            ->find();

        if ($dataRow) {
            return json([
                'code' => 1,
                'msg' => '平台账号已存在'
            ]);
        }

        $data = [
            'type' => Request::post('type'),
            'account' => Request::post('account'),
            'receiver_name' => Request::post('receiver_name'),
            'receiver_phone' => Request::post('receiver_phone'),
            'receiver_addr_province' => Request::post('receiver_addr_province'),
            'receiver_addr_city' => Request::post('receiver_addr_city'),
            'receiver_addr_county' => Request::post('receiver_addr_county'),
            'receiver_addr_content' => Request::post('receiver_addr_content'),
            'sex' => (int)Request::post('sex'),
            'age' => Request::post('age'),
            'credit_rating' => Request::post('credit_rating'),
            // 'ordernumber_any' => Request::post('ordernumber_any'),
            // 'fav_cat_1' => Request::post('fav_cat_1', 0),
            // 'fav_cat_2' => Request::post('fav_cat_2', 0),
            // 'fav_cat_3' => Request::post('fav_cat_3', 0),
            'credit_rating_img_url' => Request::post('credit_rating_img_url'),
            'realname_verify_img_url' => Request::post('realname_verify_img_url'),
            'huabei_img_url' => Request::post('huabei_img_url'),
            'userid' => session('memberInfo.userid'),
            'status' => 0,
        ];

        $dataRow = MemberBuyerPlatformInfo::field('id')->where('type', Request::post('type'))
            ->where('userid', session('memberInfo.userid'))
            ->find();

        if ($dataRow) {
            $affectedRows = MemberBuyerPlatformInfo::where('id', $dataRow['id'])->update($data);
        } else {
            $affectedRows = MemberBuyerPlatformInfo::insert($data);
        }


        if ($affectedRows !== false) {
            return json(['code' => 0]);
        } else {
            return json(['code' => 1, 'msg' => '操作失败']);
        }
    }

    public function bind_idcard()
    {
        $affectedRows = MemberBuyer::field('truename,idcardnum,idcardimgurl,idverifystatus,idrefusenote')->where('userid', session('memberInfo.userid'))->find();

        return json([
            'code' => 0,
            'data' => $affectedRows
        ]);
    }

    public function bind_idcard_post()
    {
        $dataRows = MemberBuyer::field('idverifystatus')->where('userid', session('memberInfo.userid'))->find();

        if ($dataRows['idverifystatus'] == 1) {
            return json([
                'code' => 1,
                'msg' => '已经绑定过身份'
            ]);
        }

        $validate = Validate::make([
            'truename' => 'require',
            'idcardnum' => 'require',
            'idcardimgurl' => 'require',
            'idcardimgurl2' => 'require',
            'bankaccountname' => 'require',
            'bankaccount' => 'require',
            'bankname' => 'require',
            // 'bankextinfo' => 'require',
        ])->message([
            'truename' => '请填写身份证真实姓名',
            'idcardnum' => '请填写身份号码',
            'idcardimgurl' => '请上传身份证正面和反面',
            'idcardimgurl2' => '请上传身份证正面和反面',
            'bankaccountname' => '请填写所属银行',
            'bankaccount' => '请填写银行卡号',
            'bankname' => '请填写银行卡真实姓名',
            // 'bankextinfo' => '请填写银行分行支行等详细信息',
        ]);

        if (!$validate->check(Request::post(''))) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        };


        $affectedRows = MemberBuyer::where('userid', session('memberInfo.userid'))->update([
            'truename' => Request::post('truename'),
            'idcardnum' => Request::post('idcardnum'),
            'idcardimgurl' => Request::post('idcardimgurl'),
            'idcardimgurl2' => Request::post('idcardimgurl2'),
            'idverifystatus' => 1,
            'bankaccountname' => Request::post('bankaccountname'),
            'bankaccount' => Request::post('bankaccount'),
            'bankname' => Request::post('bankname'),
            'bankextinfo' => Request::post('bankextinfo'),
        ]);

        if ($affectedRows !== false) {
            return json(['code' => 0]);
        } else {
            return json(['code' => 1, 'msg' => '没修改任何数据']);
        }
    }

    public function bind_bank_post()
    {
        $dataRows = MemberBuyer::field('bankaccountname,idverifystatus')->where('userid', session('memberInfo.userid'))->find();
        if ($dataRows->getData('idverifystatus') != 2) {
            return json([
                'code' => 1,
                'msg' => '身份证未审核通过'
            ]);
        }

        if ($dataRows['bankaccountname']) {
            return json([
                'code' => 1,
                'msg' => '已经绑定过银行'
            ]);
        }


        $validate = Validate::make([
            'bankaccountname' => 'require',
            'bankaccount' => 'require',
            'bankname' => 'require',
            'bankextinfo' => 'require',
        ]);

        if (!$validate->check(Request::post(''))) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        };

        $affectedRows = MemberBuyer::where('userid', session('memberInfo.userid'))->update([
            'bankaccountname' => Request::post('bankaccountname'),
            'bankaccount' => Request::post('bankaccount'),
            'bankname' => Request::post('bankname'),
            'bankextinfo' => Request::post('bankextinfo'),
        ]);

        if ($affectedRows !== false) {
            return json(['code' => 0]);
        } else {
            return json(['code' => 1, 'msg' => '没修改任何数据']);
        }
    }

    public function bind_qq_post()
    {
        $dataRows = MemberBuyer::field('idverifystatus')->where('userid', session('memberInfo.userid'))->find();
        if ($dataRows->getData('idverifystatus') != 2) {
            return json([
                'code' => 1,
                'msg' => '身份证未审核通过'
            ]);
        }

        $validate = Validate::make([
            'qq' => 'require',
        ]);

        if (!$validate->check(Request::post(''))) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        };


        $affectedRows = MemberBuyer::where('userid', session('memberInfo.userid'))->update([
            'qq' => Request::post('qq'),
        ]);

        if ($affectedRows !== false) {
            return json(['code' => 0]);
        } else {
            return json(['code' => 1, 'msg' => '没修改任何数据']);
        }
    }

    public function getChild()
    {
        return json([
            'code' => 0,
            'data' => MemberBuyer::getChild(session('memberInfo.userid'))
        ]);
    }


    public function accept()
    {
        return json([
            'code' => 0,
            'data' => MemberBuyerInfo::field('isaccept,maxamount')->where('userid', session('memberInfo.userid'))->find(),
        ]);
    }

    public function accept_post()
    {
        $platform = MemberBuyerPlatformInfo::where('userid', session('memberInfo.userid'))->find();

        if (!$platform || $platform['status'] != 1 && Request::post('isaccept') == 1) {
            return json(['code' => 4031, 'msg' => lang(4031)]);
        }

        $affectedRows = $platform->buyerInfo->allowField(['isaccept', 'maxamount'])->save(Request::post(''));

        if ($affectedRows !== false) {
            return json([
                'code' => 0,
                'data' => [
                    'isaccept' => Request::post('isaccept', 0),
                    'maxamount' => Request::post('maxamount', 500),
                ],
            ]);
        } else {
            return json(['code' => 1, 'msg' => '没修改任何数据']);
        }

    }

    public function appeal()
    {
        if (Request::get('usertype') == 1) {
            $appeal = Appeal::where('usertype = 1 and userid = ' . session('memberInfo.userid'))
                ->order(['appealtime' => 'desc'])
                ->paginate(20);
        } else {
            $appeal = Appeal::where('usertype = 0 and touserid = ' . session('memberInfo.userid'))
                ->order(['appealtime' => 'desc'])
                ->paginate(20);
        }

        return json([
            'code' => 0,
            'data' => $appeal
        ]);
    }


    public function bind()
    {
        $platform = MemberBuyerPlatformInfo::field('type,status,status as statusText')->where('userid', session('memberInfo.userid'))->select();
        $bind = [];
        foreach ($platform as $vo) {
            $bind[$vo['type']] = $vo;
        }
        return json([
            'code' => 0,
            'data' => $bind
        ]);
    }

    public function bind_taobao_detail_hightquality()
    {
        $platform = MemberBuyerPlatformInfo::field('hq_account_status,hq_op_reason')->where('userid', session('memberInfo.userid'))->find();
        return json([
            'code' => 0,
            'data' => $platform
        ]);
    }

    public function bind_taobao_detail_hightquality_post()
    {
        $platform = MemberBuyerPlatformInfo::field('hq_account_status')->where('userid', session('memberInfo.userid'))->find();
        if ($platform->getData('hq_account_status') == 2) {
            return json(['code' => 1, 'msg' => '已审核成功']);
        }
        if ($platform->getData('hq_account_status') == 1) {
            return json(['code' => 1, 'msg' => '已在审核中']);
        }
        $affectedRows = MemberBuyerPlatformInfo::where('userid', session('memberInfo.userid'))->update([
            'hq_account_status' => 1,
            'hq_apply_time' => \tool\Date::date(),
        ]);

        if ($affectedRows !== false) {
            return json([
                'code' => 0
            ]);
        } else {
            return json(['code' => 1, 'msg' => '提交失败']);
        }
    }

    public function promotion()
    {
        return json([
            'code' => 0,
            'data' => [
                'userid' => session('memberInfo.userid'),
                'count' => DB::name('promotion')->where('up1_userid', session('memberInfo.userid'))->count(),
            ]
        ]);
    }

    public function scoreLog()
    {
        return json(['code' => 0, 'data' => DB::name('member_buyer_score_log')->where('userid', session('memberInfo.userid'))->order('addtime', 'desc')->paginate(20)]);
    }

    public function myPromotion()
    {
        if (Request::get('type') == 1) {
            $promotionList = DB::name('promotion')->where('up1_userid', session('memberInfo.userid'))->select();
        } else {
            $promotionList = DB::name('promotion')->where('up2_userid', session('memberInfo.userid'))->select();
        }

        return json([
            'code' => 0,
            'data' => $promotionList
        ]);
    }

    public function qrCode()
    {
        $im_path = 'uploadfile/images/qrCode.png';
        //创建图片的实例
        $im = imagecreatefrompng($im_path);
        // //打上文字
        $font = 'uploadfile/fonts/STLITI.TTF';//字体
        $color = imagecolorallocate($im, 255, 255, 255);
        imagefttext($im, 42, 0, 380, 1330, $color, $font, '邀请码：' . session('memberInfo.userid'));
        //输出图片
        list($im_w, $im_h, $im_type) = getimagesize($im_path);
        switch ($im_type) {
            case 1://GIF
                header('Content-Type: image/gif');
                imagegif($im);
                break;
            case 2://JPG
                header('Content-Type: image/jpeg');
                imagejpeg($im);
                break;
            case 3://PNG
                header('Content-Type: image/png');
                imagepng($im);
                break;
            default:
                break;
        }
        // imagedestroy($dst);
        exit;
    }

    public function edit_avatar_post()
    {
        $affectedRows = MemberBuyer::where('userid', session('memberInfo.userid'))->update(['avatar' => Request::post('avatar')]);

        if ($affectedRows !== false) {
            return json([
                'code' => 0
            ]);
        } else {
            return json(['code' => 1, 'msg' => '没修改任何数据']);
        }
    }

    public function AppIconBadge()
    {
        return json([
            'code' => 0,
            'data' => Order::where('userid', session('memberInfo.userid'))->where('status', 2)->count()
        ]);
    }
}
